package com.sy.simpleegg.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.lifecycleScope
import androidx.viewpager.widget.PagerAdapter
import com.sy.simpleegg.R
import com.sy.simpleegg.base.BaseMvpFragment
import com.sy.simpleegg.constant.Constant
import com.sy.simpleegg.constant.Constant.CHANNEL_COUNT_DEFAULT
import com.sy.simpleegg.constant.Constant.STOCK_MAX_DEFAULT
import com.sy.simpleegg.databinding.FragmentBackstageBinding
import com.sy.simpleegg.event.ControllerHeartBeatEvent
import com.sy.simpleegg.event.ExitAppEvent
import com.sy.simpleegg.event.LyyBoxHeartBeatEvent
import com.sy.simpleegg.event.StartClearCoinsEvent
import com.sy.simpleegg.event.StopClearCoinsEvent
import com.sy.simpleegg.event.SupplementCoinsEvent
import com.sy.simpleegg.event.SupplementCoinsFinishEvent
import com.sy.simpleegg.event.SwitchFragmentEvent
import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.mvp.contract.BackstageContract
import com.sy.simpleegg.mvp.presenter.BackstagePresenter
import com.sy.simpleegg.ui.fragment.config.FragmentEnum
import com.sy.simpleegg.ui.layout.TouchLinearLayout
import com.sy.simpleegg.util.Preference
import com.sy.verticaltablayout.VerticalTabLayout.OnTabSelectedListener
import com.sy.verticaltablayout.adapter.TabAdapter
import com.sy.verticaltablayout.widget.ITabView.TabBadge
import com.sy.verticaltablayout.widget.ITabView.TabIcon
import com.sy.verticaltablayout.widget.ITabView.TabTitle
import com.sy.verticaltablayout.widget.TabView
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class BackstageFragment :
    BaseMvpFragment<BackstageContract.View, BackstageContract.Presenter, FragmentBackstageBinding>(),
    BackstageContract.View {

    companion object {
        fun getInstance(): BackstageFragment = BackstageFragment()
    }

    private var fastManageFragment: FastManageFragment? = null
    private var deviceManageFragment: DeviceManageFragment? = null
    private var packageManageFragment: PackageManageFragment? = null
    private var operatingStatisticsFragment: OperatingStatisticsFragment? = null
//    private var logManageFragment: LogManageFragment? = null
    private var configFragment: ConfigFragment? = null
    private var supplementFragment: SupplementFragment? = null
//    private var textFragment: TextFragment? = null

    private var boxAnimation: Animation? = null
    private var controlAnimation: Animation? = null

    private var controlHeartBeat = Constant.COINCONTROL_HEARTBEAT
    private var boxHeartBeat = Constant.BOX_HEARTBEAT

    private var isOuting = false

    /**
     * 设备编号
     */
    private var devNumber: String by Preference(Constant.SETTING_DEVICE_NUMBER, "")

    /**
     * 货道数量
     */
    private var channelCount: Int by Preference(
        Constant.SETTING_CHANNEL_COUNT,
        CHANNEL_COUNT_DEFAULT
    )

    /**
     * 库存最大值
     */
    private var stockMax: Int by Preference(Constant.SETTING_STOCK_MAX, STOCK_MAX_DEFAULT)

    override fun createPresenter(): BackstageContract.Presenter = BackstagePresenter(lifecycleScope)

    override fun attachLayoutRes(): Int = R.layout.fragment_backstage

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        openEventBus = true
    }

    override fun initView(view: View) {
        super.initView(view)
//        binding.btnLogout.setOnClickListener {
//            showExitDialog()
//        }
//        binding.itemPassword.setOnClickListener {
//            logFile("点击修改密码")
//            forwardTo(FragmentEnum.PASSWORD)
//        }
//        binding.itemHome.setOnClickListener {
//            logFile("点击主页设置")
//            forwardTo(FragmentEnum.MAIN_SETTING)
//        }
//        binding.itemChannel.setOnClickListener {
//            logFile("点击货道设置")
//            forwardTo(FragmentEnum.CHANNEL_SETTING)
//        }
//        binding.itemControlChannel.setOnClickListener {
//            logFile("点击控制板货道参数")
//            forwardTo(FragmentEnum.CONTROL_CHANNEL_PARAM)
//        }
//        binding.itemControlExt.setOnClickListener {
//            logFile("点击控制板外置参数")
//            forwardTo(FragmentEnum.CONTROL_EXT)
//        }
//        binding.itemWifi.setOnClickListener {
//            logFile("点击WIFI配置")
//            forwardTo(FragmentEnum.WIFI)
//        }
//        binding.itemApp.setOnClickListener {
//            logFile("点击APP设置")
//            forwardTo(FragmentEnum.APP)
//        }
//        binding.itemAbout.setOnClickListener {
//            logFile("点击About")
//            forwardTo(FragmentEnum.ABOUT)
//        }
//        binding.tvDeviceNumber.text = devNumber
//        binding.tvChannelCount.text = channelCount.toString()
//        binding.tvStockMax.text = stockMax.toString()

        binding.btnExitBackstage.setOnClickListener {
            EventBus.getDefault().post(SwitchFragmentEvent(FragmentEnum.HOME))
        }

        binding.btnExitApp.setOnClickListener {
            EventBus.getDefault().post(ExitAppEvent(0))
        }

        binding.tabLayout.setTabAdapter(
            MyTabAdapter(
                mutableListOf(
                    getString(R.string.fast_manage),
                    getString(R.string.device_manage),
                    getString(R.string.order_supplement),
//                    getString(R.string.package_manage),
                    getString(R.string.operating_statistics),
//                    getString(R.string.log_manage),
//                    getString(R.string.text_manage)
                )
            )
        )
        binding.tabLayout.addOnTabSelectedListener(object : OnTabSelectedListener {
            override fun onTabSelected(tab: TabView?, position: Int) {
                showTargetFragment(position)
            }

            override fun onTabReselected(tab: TabView?, position: Int) {
                logFile("重选tab position=$position")
            }
        })

        binding.llTouch.setTouchListener(object : TouchLinearLayout.TouchListener {
            override fun touch() {
                if (isOuting) return
                startCountDown()
            }
        })

        refreshControlHeartBeat()
        refreshBoxHeartBeat()

        showTargetFragment(0)
    }

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
    ): FragmentBackstageBinding {
        return FragmentBackstageBinding.inflate(inflater, container, false)
    }

    override fun lazyLoad() {

    }

    override fun onResume() {
        super.onResume()
        logFile("${javaClass.simpleName} onResume")
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden) {
            logFile("${javaClass.simpleName}隐藏")
        } else {
            logFile("${javaClass.simpleName}显示")
        }
    }


    override fun showLoading() {

    }

    override fun hideLoading() {

    }

    /**
     * 显示目标Fragment
     * @param position MyTabAdapter传入列表数据的index
     */
    private fun showTargetFragment(position: Int) {
        try {
            val transaction = childFragmentManager.beginTransaction()
            hideFragment(transaction)

            when (position) {
                0 -> {
                    if (fastManageFragment == null) {
                        fastManageFragment = FastManageFragment.getInstance()
                        transaction.add(
                            R.id.main_container,
                            fastManageFragment!!,
                            "FastManageFragment"
                        )
                    } else {
                        transaction.show(fastManageFragment!!)
                    }
                }

                1 -> {
//                    if (deviceManageFragment == null) {
//                        deviceManageFragment = DeviceManageFragment.getInstance()
//                        transaction.add(
//                            R.id.main_container,
//                            deviceManageFragment!!,
//                            "DeviceManageFragment"
//                        )
//                    } else {
//                        transaction.show(deviceManageFragment!!)
//                    }
                    if (configFragment == null) {
                        configFragment = ConfigFragment.getInstance()
                        transaction.add(
                            R.id.main_container,
                            configFragment!!,
                            "ConfigFragment"
                        )
                    } else {
                        transaction.show(configFragment!!)
                    }
                }

//                2 -> {
//                    if (packageManageFragment == null) {
//                        packageManageFragment = PackageManageFragment.getInstance()
//                        transaction.add(
//                            R.id.main_container,
//                            packageManageFragment!!,
//                            "PackageManageFragment"
//                        )
//                    } else {
//                        transaction.show(packageManageFragment!!)
//                    }
//                }

                2 -> {
                    if (supplementFragment == null) {
                        supplementFragment = SupplementFragment.getInstance()
                        transaction.add(
                            R.id.main_container,
                            supplementFragment!!,
                            "SupplementFragment"
                        )
                    } else {
                        transaction.show(supplementFragment!!)
                    }
                }

                3 -> {
                    if (operatingStatisticsFragment == null) {
                        operatingStatisticsFragment = OperatingStatisticsFragment.getInstance()
                        transaction.add(
                            R.id.main_container,
                            operatingStatisticsFragment!!,
                            "OperatingStatisticsFragment"
                        )
                    } else {
                        transaction.show(operatingStatisticsFragment!!)
                    }
                }

//                4 -> {
//                    if (logManageFragment == null) {
//                        logManageFragment = LogManageFragment.getInstance()
//                        transaction.add(
//                            R.id.main_container,
//                            logManageFragment!!,
//                            "LogManageFragment"
//                        )
//                    } else {
//                        transaction.show(logManageFragment!!)
//                    }
//                }

//                5 -> {
//                    if (textFragment == null) {
//                        textFragment = TextFragment.getInstance()
//                        transaction.add(
//                            R.id.main_container,
//                            textFragment!!,
//                            "TextFragment"
//                        )
//                    } else {
//                        transaction.show(textFragment!!)
//                    }
//                }
            }
            transaction.commit()
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("显示目标Fragment异常：${e.message}")
        }
    }

    private fun hideFragment(transaction: FragmentTransaction) {
        try {
            fastManageFragment?.let {
                transaction.remove(it)
                fastManageFragment = null
            }
            deviceManageFragment?.let {
                transaction.remove(it)
                deviceManageFragment = null
            }
            packageManageFragment?.let {
                transaction.remove(it)
                packageManageFragment = null
            }
            operatingStatisticsFragment?.let {
                transaction.remove(it)
                operatingStatisticsFragment = null
            }
//            logManageFragment?.let {
//                transaction.remove(it)
//                logManageFragment = null
//            }
            configFragment?.let {
                transaction.remove(it)
                configFragment = null
            }
            supplementFragment?.let {
                transaction.remove(it)
                supplementFragment = null
            }
//            textFragment?.let {
//                transaction.remove(it)
//                textFragment = null
//            }
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("隐藏Fragment异常：${e.message}")
        }
    }

    private inner class MyTabAdapter(var tabs: List<String>) : PagerAdapter(), TabAdapter {
        override fun getCount(): Int {
            return tabs.size
        }

        override fun isViewFromObject(view: View, `object`: Any): Boolean {
            return view === `object`
        }

        override fun getBadge(position: Int): TabBadge? {
            return null
        }

        override fun getIcon(position: Int): TabIcon? {
            return null
        }

        override fun getTitle(position: Int): TabTitle {
            return TabTitle.Builder()
                .setContent(tabs[position])
                .setTextColor(-0xe57a01, -0xf5e2cd)
                .setTextSize(11)
                .build()
        }

        override fun getBackground(position: Int): Int {
            return 0
        }
    }


    private fun showExitDialog() {
//        val exitDialog = ExitDialog(
//            resources.getString(R.string.bs_logout),
//            resources.getString(R.string.logout_content),
//            object : ExitDialog.ExitDialogListener{
//                override fun dismiss() {
//                    startCountDown()
//                }
//
//                override fun negative() {
//
//                }
//
//                override fun positive() {
//                    EventBus.getDefault().post(SwitchFragmentEvent(FragmentEnum.HOME))
//                }
//
//            })
//        exitDialog.showNow(parentFragmentManager, "LogoutBackstage")
//        cancelCountDown()
    }

    private fun forwardTo(fragment: FragmentEnum) {
        EventBus.getDefault().post(SwitchFragmentEvent(fragment))
    }

    private fun refreshControlHeartBeat(){
        try {
            controlAnimation?.cancel()
            controlAnimation = AnimationUtils.loadAnimation(requireContext(), R.anim.scaleanim).apply {
                if (controlHeartBeat){
                    binding.ivState.setImageResource(R.drawable.online)
                    duration = 1000
                }else{
                    binding.ivState.setImageResource(R.drawable.offline)
                    duration = 300
                }
                binding.ivState.animation = this
                start()
            }
            binding.tvErr.text = when (Constant.COINCONTROL_ERR_CODE.toString()) {
                "1" -> getString(R.string.err_no_coin)
                "2" -> getString(R.string.err_ka_coin)
                "3" -> getString(R.string.err_lock)
                "16" -> getString(R.string.err_other)
                else -> getString(R.string.no_err)
            }
        }catch (e: Exception){
            e.printStackTrace()
            logFile("刷新控制板信号状态异常：${e.message}")
        }
    }

    private fun refreshBoxHeartBeat(){
        try {
            boxAnimation?.cancel()
            boxAnimation = AnimationUtils.loadAnimation(requireContext(), R.anim.scaleanim).apply {
                if (boxHeartBeat){
                    binding.ivBoxState.setImageResource(R.drawable.online)
                    duration = 1000
                }else{
                    binding.ivBoxState.setImageResource(R.drawable.offline)
                    duration = 300
                }
                binding.ivBoxState.animation = this
                start()
            }
        }catch (e: Exception){
            e.printStackTrace()
            logFile("刷新盒子信号状态异常：${e.message}")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun controllerHeartBeatEvent(event: ControllerHeartBeatEvent) {
        try {
            logFile("刷新控制板信号事件：${event}")
            if (event.connect != controlHeartBeat){
                controlHeartBeat = event.connect
                refreshControlHeartBeat()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("刷新控制板信号事件异常：${e.message}")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun lyyBoxHeartBeatEvent(event: LyyBoxHeartBeatEvent) {
        try {
            logFile("刷新盒子信号事件：${event}")
            if (event.connect != boxHeartBeat){
                boxHeartBeat = event.connect
                refreshBoxHeartBeat()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("刷新盒子信号事件异常：${e.message}")
        }
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    fun startClearCoinsEvent(event: StartClearCoinsEvent) {
        logFile("开始清币事件2")
        isOuting = true
        cancelCountDown()
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    fun stopClearCoinsEvent(event: StopClearCoinsEvent) {
        logFile("结束清币事件")
        isOuting = false
        startCountDown()
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    fun supplementCoinsEvent(event: SupplementCoinsEvent) {
        logFile("异常订单补币事件，取消倒计时")
        isOuting = true
        cancelCountDown()
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    fun supplementCoinsFinishEvent(event: SupplementCoinsFinishEvent) {
        logFile("异常订单补币结束事件，开启倒计时")
        isOuting = false
        startCountDown()
    }
}